import moment from 'moment';
import qs from 'qs';
import Errand from '../../../Models/errand';
import User from '../../../Models/user';
import Money from '../../../Models/money';
import HsPay from '../../../Models/hspay';
import { getCreator } from '../../../utils/util';
import { constantObj } from '../../../utils/constants'
import { saveNotice, getNewPoints, getPayData } from '../utils/';
const crypto = require('crypto');
const SHA256 = require("crypto-js/sha256");

const FormData = require('form-data');
const fetch = require('node-fetch');
const errandEntity = new Errand();
const userEntity = new User();
const moneyEntity = new Money();
const hsPayEntity = new HsPay();

export function getPaotuiList(req, res, next) {
    const { ...query } = req.body;
    query.status = 1;
    errandEntity.getErrands(query, (err, errands, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: errands, total, hasMore } });
    })
}

export function getMyPaotuiList(req, res, next) {
    const { ...query } = req.body;
    query.creatorId = req.user._id;
    errandEntity.getErrands(query, (err, errands, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: errands, total, hasMore } });
    })
}

export function getMyObtainPaotuiList(req, res, next) {
    const { ...query } = req.body;
    query.getterId = req.user._id;
    errandEntity.getErrands(query, (err, errands, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: errands, total, hasMore } });
    })
}

export function getMyObtainMoney(req, res, next) {
    const { ...query } = req.body;
    query.getterId = req.user._id;
    errandEntity.getAllErrands(query, (err, errands) => {
        const price = errands.reduce((t, c) => {
            t += c.price;
            return t;
        }, 0)
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: price });
    })
}

export function getErrands(req, res, next) {
    const { ...query } = req.body;
    errandEntity.getErrands(query, (err, errands, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: errands, total, hasMore } });
    })
}

export function getErrand(req, res, next) {
    const { ...query } = req.body;
    errandEntity.getErrand(query, (err, errands) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json(errands);
    })
}

// export function getAllErrands(req, res, next) {
//     userEntity.getAllErrands({}, (err, users) => {
//         if (err) {
//             return res.status(200).json({ code: 1, msg: '服务器开小差' });
//         }
//         return res.status(200).json({ code: 0, data: users.filter((user) => user.name !== 'admin') });
//     })
// }

// 建立订单
// export function createPaotui(req, res, next) {
//     const { ...errand } = req.body;
//     const creator = getCreator(req.user);
//     errand.creatorId = creator._id;
//     errand.creator = creator;

//     userEntity.getUser({
//         _id: creator._id
//     }, (err, user) => {
//         if (err) {
//             return res.status(200).json({ code: 1, msg: '服务器开小差' });
//         }
//         const errandEntity = new Errand();
//         if (user.money > errand.price) {
//             errand.status = 1;
//             errandEntity.saveErrand(errand, (err, newErrand) => {
//                 if (err) {
//                     return res.status(200).json({ code: 1, msg: '服务器开小差' });
//                 }
//                 const moneyEntity = new Money();
//                 const money = {
//                     fromUserId: creator._id,
//                     toUserId: 'system',
//                     errandId: newErrand._id,
//                     money: errand.price,
//                     msg: '发布跑腿',
//                     payTool: 2,
//                 }
//                 // getNewPoints (creator._id, '发布跑腿', 3) 
//                 moneyEntity.saveMoney(money, err => {
//                     if (err) {
//                         return res.status(200).json({ code: 1, msg: '服务器开小差' });
//                     }
//                     userEntity.updateUser({ _id: user._id, money: user.money - errand.price }, err => {
//                         if (err) {
//                             return res.status(200).json({ code: 1, msg: '服务器开小差' });
//                         }
//                         return res.status(200).json({ code: 0, data: '' });
//                     })
//                 })
//             });
//         } else {
//             errand.status = 0;
//             errandEntity.saveErrand(errand, (err, newErrand) => {
//                 if (err) {
//                     return res.status(200).json({ code: 1, msg: '服务器开小差' });
//                 }
//                 const body = getPayData('跑腿服务', errand.price, errand.desc, errand.channel_id || '021', "http://111.231.87.118:3001/api/getHSPayResult")
//                 fetch('http://121.43.72.206:6201/eis/yunpay/epay_wallet_pay', {
//                     method: 'POST', body, headers: {
//                         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
//                     }
//                 })
//                     .then(res => res.json())
//                     .then(json => {
//                         const hsPayBack = json.data[0] || {};
//                         // console.log(hsBack, 888);
//                         const hsPayEntity = new HsPay();
//                         hsPayEntity.saveHsPay({ channel_serial_no: hsPayBack.channel_serial_no, hsPayBack, targetId: newErrand._id }, (err, hspay) => {
//                             if (err) {
//                                 return res.status(200).json({ code: 1, data: 服务器开小差 });
//                             }
//                             // return res.status(200).json({ code: 0, data: {_id: hspay._id, view: hsPayBack.view} });
//                             return res.status(200).json({ code: 0, data: hsPayBack.view });
//                         })
//                     });
//             });
//         }
//     })
// }
export function createPaotui(req, res, next) {
    const { ...errand } = req.body;
    const creator = getCreator(req.user);
    errand.creatorId = creator._id;
    errand.creator = creator;

    const errandEntity = new Errand();
    errand.status = 1;
    errandEntity.saveErrand(errand, (err) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function getPayParams(req, res, next) {

    // 生成参数
    const { channel_id, occur_balance, prod_name, summary } = req.body;
    const body = getPayData(prod_name, occur_balance, summary, channel_id || '021', "http://111.231.87.118:3001/api/getHSPayResult")

    fetch('http://121.43.72.206:6201/eis/yunpay/epay_wallet_pay', {
        method: 'POST', body, headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        }
    })
        .then(res => res.json())
        .then(json => {
            const data = json.data[0];
            console.log(data)
            return res.status(200).json({ code: 0, data: json });
        });
}

// to hs
export function getHSPayResult(req, res, next) {
    const hsTuiSong = req.body;
    const hsPayEntity = new HsPay();
    hsPayEntity.saveHsPay({ hsTuiSong }, err => {
        if (err) {
            return res.status(200).json({ code: 1, data: '服务器开小差' });
        }
        return res.status(200).json('success');
    });
    // hsPayEntity.getHsPay({_id}, (err, hspay) => {
    //     if (err) {
    //         return res.status(200).json({ code: 1, msg: '服务器开小差' });
    //     }

    //     errandEntity.getErrand({ _id: hspay.targetId }, (err, errand) => {
    //         if (err || !errand) {
    //             return res.status(200).json({ code: 1, msg: '服务器开小差' });
    //         }
    //         const obj = {
    //             _id: hspay.targetId,
    //             status: 1
    //         }
    //         errandEntity.updateErrand(obj, err => {
    //             if (err) {
    //                 return res.status(200).json({ code: 1, msg: '服务器开小差' });
    //             }
    //             const moneyEntity = new Money();
    //             const money = {
    //                 fromUserId: creator._id,
    //                 toUserId: 'system',
    //                 errandId: hspay.targetId,
    //                 money: errand.price,
    //                 msg: '发布跑腿',
    //                 payTool: 1,
    //             }
    //             moneyEntity.saveMoney(money, err=>{
    //                 if (err) {
    //                     return res.status(200).json({ code: 1, msg: '服务器开小差' });
    //                 }
    //                 return res.status(200).json({ code: 0 });
    //             })
    //         });
    //     })
    // });
}

// 获取恒生的推送的列表
export function getHsPays(req, res, next) {
    hsPayEntity.getHsPays({ current: 1, pageSize: 100 }, (err, errands, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: errands, total, hasMore } });
    });
}

// to app
export function getPayResult(req, res, next) {
    const { _id } = req.body;
    const creator = getCreator(req.user);
    hsPayEntity.getHsPay({ _id }, (err, hspay) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }

        errandEntity.getErrand({ _id: hspay.targetId }, (err, errand) => {
            if (err || !errand) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            const obj = {
                _id: hspay.targetId,
                status: 1
            }
            errandEntity.updateErrand(obj, err => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                const moneyEntity = new Money();
                const money = {
                    fromUserId: creator._id,
                    toUserId: 'system',
                    errandId: hspay.targetId,
                    money: errand.price,
                    msg: '发布跑腿',
                    payTool: 1,
                }
                moneyEntity.saveMoney(money, err => {
                    if (err) {
                        return res.status(200).json({ code: 1, msg: '服务器开小差' });
                    }
                    return res.status(200).json({ code: 0 });
                })
            });
        })
    });
}

// 抢单
export function obtainPaotui(req, res, next) {
    const { ...errand } = req.body;
    errandEntity.getErrand({ _id: errand._id }, (err, errand) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const { getterId } = errand;
        if (getterId) {
            return res.status(200).json({ code: 1, msg: '该单已被抢' });
        }
        const creator = getCreator(req.user);
        errand.getter = creator;
        errand.getterId = creator._id;
        errand.status = 2;
        errandEntity.updateErrand(errand, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            // getNewPoints (creator._id, '接单跑腿', 4) 
            return res.status(200).json({ code: 0 });
        });
    })
}

// 跑手确认，传入2.5
// 发布者确认，传入3
export function confirmPaotui(req, res, next) {
    const { _id, status } = req.body;
    errandEntity.updateErrand({ _id, status }, err => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}


export function cancelPaotui(req, res, next) {
    const { ...errand } = req.body;
    const creator = getCreator(req.user);

    errandEntity.getErrand({ _id: errand._id }, (err, errand) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (creator._id !== errand.creatorId) {
            return res.status(200).json({ code: 1, msg: '不能取消其他人的订单' });
        }
        errandEntity.updateErrand({ _id: creator._id, status: -1 }, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    })
}

export function cancelObtainPaotui(req, res, next) {
    const { ...errand } = req.body;
    const creator = getCreator(req.user);

    errandEntity.getErrand({ _id: errand._id }, (err, errand) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (creator._id !== errand.getterId) {
            return res.status(200).json({ code: 1, msg: '不能取消其他人的订单' });
        }
        errandEntity.updateErrand({ _id: creator._id, status: -1 }, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    })
}

export function finishPaotui(req, res, next) {
    const { ...errand } = req.body;
    const creator = getCreator(req.user);
    errandEntity.getErrand({ _id: errand._id }, (err, errand) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (creator._id !== errand.creatorId) {
            return res.status(200).json({ code: 1, msg: '不能完成其他人的订单' });
        }
        errandEntity.updateErrand({ _id: creator._id, status: 3 }, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    })
}

export function cmtPaotui(req, res, next) {
    const { msg, _id } = req.body;
    const creator = getCreator(req.user);
    errandEntity.getErrand({ _id }, (err, errand) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const obj = {
            _id
        }
        if (errand.creatorId === creator._id) {
            // 建立者评论
            obj.isCreatorCmt = true,
                obj.creatorMsg = msg
        }
        if (errand.getterId === creator._id) {
            // 接单者评论
            obj.isGetterCmt = true,
                obj.GetterMsg = msg
        }
        errandEntity.updateErrand(obj, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            // getNewPoints (creator._id, '评价跑腿', 1) 
            return res.status(200).json({ code: 0 });
        });
    })
}

// export function updateErrand(req, res, next) {
//     const {  ...errand } = req.body;
//     const errandEntity = new Errand();
//     if (!errand._id) {
//         errandEntity.saveErrand(errand, err => {
//             if (err) {
//                 return res.status(200).json({ code: 1, msg: '服务器开小差' });
//             }
//             return res.status(200).json({ code: 0 });
//         });
//     } else {
//         errandEntity.updateErrand(errand, err => {
//             if (err) {
//                 return res.status(200).json({ code: 1, msg: '服务器开小差' });
//             }
//             return res.status(200).json({ code: 0 });
//         });
//     }
// }

export function removeErrands(req, res, next) {
    const errandIds = req.body.errandIds;

    errandEntity.removeErrands(errandIds, (err, errand) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}
